<?php
	//setting up session variables so results are remembered when clicking away from this page and then coming back later
	//initialize search variables
	if(!isset($_SESSION['nomination_search']) || !isset($_SESSION['nomination_field'])) {
		$_SESSION['nomination_search'] = '';
		$_SESSION['nomination_field'] = 'contestant.url';
	}
	//initialize sort variables
	if(!isset($_SESSION['nomination_sort'])) {
		$_SESSION['nomination_sort'] = 'category.name';
		$_SESSION['nomination_order'] = 'asc';
	}
	//initialize record display counter/limiter
	if(!isset($_SESSION['nomination_count'])) {
		$_SESSION['nomination_count'] = 10;
		$_SESSION['nomination_count_from'] = 0;
	}


	if(isset($_POST['search_submit']) || isset($_GET['action']) || isset($_GET['type']) || isset($_GET['sort']) || isset($_GET['countprevious']) || isset($_GET['countnext']) || isset($_GET['filtercount']) || isset($_GET['filterpage']) || isset($_GET['reset'])) {
		//page and resultset controls
		if($_GET['filtercount']) $_SESSION['nomination_count'] = $_GET['filtercount'];
		if($_GET['filterpage']) $_SESSION['nomination_count_from'] = ($_GET['filterpage']-1)*$_SESSION['nomination_count'];
		if($_GET['countprevious']) {
			if($_SESSION['nomination_count_from']-$_SESSION['nomination_count']<=0) $_SESSION['nomination_count_from'] = 0;
			else $_SESSION['nomination_count_from'] = $_SESSION['nomination_count_from'] - $_SESSION['nomination_count'];
		}
		if($_GET['countnext']) $_SESSION['nomination_count_from'] = $_SESSION['nomination_count_from'] + $_SESSION['nomination_count'];
		
		if($_GET['reset']) {
			$_SESSION['nomination_search'] = '';
			$_SESSION['nomination_field'] = 'contestant.url';
			$_SESSION['filtercategory'] = '';
			$_SESSION['filterconfirmed'] = '';
		}
		
		//nomniation and vote actions
		if($_GET['action']=='confirm') {
			if($_GET['type']=='nomination') confirm_nomination($_GET['user_id'], $_GET['nomination_id']);
			if($_GET['type']=='vote') confirm_vote($_GET['user_id'], $_GET['nomination_id']);
		}
		if($_GET['action']=='delete') {
			if($_GET['type']=='nomination') delete_nomination($_GET['user_id'], $_GET['nomination_id']);
			if($_GET['type']=='vote') delete_vote($_GET['user_id'], $_GET['nomination_id']);
		}
		if($_GET['action']=='markceleb') mark_celeb($_GET['user_id'], $_GET['status']);
		if($_GET['action']=='membervote') member_vote($_GET['nomination_id'], $_GET['status']);
		
		//get results
		if(!isset($_GET['sort'])) $_GET['sort'] = '';
		if(!isset($_POST['filtercategory'])) $_POST['filtercategory'] = '';
		if(!isset($_POST['filterconfirmed'])) $_POST['filterconfirmed'] = '';
		if(!isset($_POST['search'])) $_POST['search'] = '';
		if(!isset($_POST['searchfield'])) $_POST['searchfield'] = '';
		$results = filter_nominations($_POST['filtercategory'], $_POST['filterconfirmed'], $_GET['sort'], $_POST['search'], $_POST['searchfield']);

		//if executing via ajax, return results
		if(isset($_GET['ajax'])) {
			echo $results;
			exit;
		}		
	}

	
	//display filtered results
	function filter_nominations($filter_category, $filter_confirmed, $sort, $search, $field) {
		global $url;
		$db = new CDatabase();
		$db->Connect();
		
		//flag whether to show votes or nominations
		if($url[1]=='votes') $param = 'vote';
		else $param = 'nomination';
		//flag whether to show the detailed search results or the grouped search results
		if($url[1]=='individual' || $url[1]=='votes') $detail = true;
		else $detail = false;
		
		//set session variables
		if(trim($filter_category)) $_SESSION['filtercategory'] = $filter_category;
		if(trim($filter_confirmed)) $_SESSION['filterconfirmed'] = $filter_confirmed;
		if(trim($sort)) {
			if($sort==$_SESSION['nomination_sort']) {
				if($_SESSION['nomination_order'] == 'desc') $_SESSION['nomination_order'] = 'asc';
				else $_SESSION['nomination_order'] = 'desc';
			}	else {
				$_SESSION['nomination_sort'] = $sort;
				$_SESSION['nomination_order'] = 'asc';
			}
		}
		if(trim($search)) $_SESSION['nomination_search'] = $search;
		if(trim($field)) $_SESSION['nomination_field'] = $field;
	
	
		//The Query
		if($detail) $qry = "SELECT DISTINCT user.email, category.name, contestant.url, user_".$param.".confirmed, user.id, nomination.id, user.celeb";
		else $qry = "SELECT DISTINCT category.name, contestant.url, nomination.nomination_count, nomination.vote_count, nomination.id";
		$qry .= " FROM contestant, category, nomination, user, user_".$param."
							WHERE nomination.category_id = category.id
							AND nomination.contestant_id = contestant.id
							AND nomination.id = user_".$param.".nomination_id
							AND user_".$param.".user_id = user.id
							AND ".$_SESSION['nomination_field']." LIKE '%".$_SESSION['nomination_search']."%'";
		if($_SESSION['filtercategory']) $qry .= " AND category.id = '".$_SESSION['filtercategory']."'";
		if($_SESSION['filterconfirmed']=='1' || $_SESSION['filterconfirmed']=='0') $qry .= " AND user_".$param.".confirmed = '".$_SESSION['filterconfirmed']."'";
		$qry .= " ORDER BY ".$_SESSION['nomination_sort']." ".$_SESSION['nomination_order'].";";
		$db->Query($qry);
		$results = $db->getResults();
		$total_rows = $db->rowsnumber;
		$curr_page = ceil(($_SESSION["nomination_count_from"]/$_SESSION["nomination_count"]) + 1);
		$total_page = ceil($total_rows/$_SESSION["nomination_count"]);
		
		$return = "<p><span style='padding-left:10px;padding-right:20px;'>
							<b>Nominations per Page: </b>
							<select id='filtercount' name='filtercount' onchange=\"return nominations_per_page();\">";
							for($i=1; $i<=$total_rows; $i++) {
								$return .= "<option value='".$i."' "; if($_SESSION['nomination_count']==$i) $return .= "selected='selected'"; $return .= ">".$i."</option>";
								if($i>=2000) $i+=49;
								else if($i>=1000) $i+=19;
								else if($i>=500) $i+=9;
								else if($i>=100) $i+=4;
							}
		$return .= "</select>
							</span>";
		if($curr_page > 1) $return .= "<a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?countprevious=1' class='button' onclick=\"return previous_page();\">< Previous</a>";
		$return .= "<select id='filterpage' name='filterpage' onchange=\"return change_page();\">";
		for($i=1; $i<=$total_page; $i++) {
			$return .= "<option value='".$i."' "; if((($_SESSION["nomination_count_from"]/$_SESSION["nomination_count"])+1)==$i) $return .= "selected='selected'"; $return .= ">Page ".$i." of ".$total_page."</option>";
		}
		$return .= "</select>";
		if($curr_page < $total_page) $return .= "<a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?countnext=1' class='button' onclick=\"return next_page();\">Next ></a></p>";

		$count = 0;
		if($total_rows) {	
			//display column headings
			$return .= "<table border='0' cellspacing='0' cellpadding='5'>
										<tr bgcolor='#ECF5FC'>";
			if($detail) { $return .= "<td><nobr><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?sort=user.email' onclick=\"return do_search('user.email');\">"; if($_SESSION['nomination_sort']=='user.email') $return .= "<img src='".HTTP_SERVER.IMG_DIR.$_SESSION['nomination_order'].".png' /> "; $return .= "<b>User Email</b></a></nobr></td>"; }
					$return .= "<td><nobr><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?sort=category.name' onclick=\"return do_search('category.name');\">"; if($_SESSION['nomination_sort']=='category.name') $return .= "<img src='".HTTP_SERVER.IMG_DIR.$_SESSION['nomination_order'].".png' /> "; $return .= "<b>Category</b></a></nobr></td>
											<td><nobr><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?sort=contestant.url' onclick=\"return do_search('contestant.url');\">"; if($_SESSION['nomination_sort']=='contestant.url') $return .= "<img src='".HTTP_SERVER.IMG_DIR.$_SESSION['nomination_order'].".png' /> "; $return .= "<b>Blog URL</b></a></nobr></td>";
			if($detail) {
				$return .= "<td><nobr><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?sort=user_".$param.".confirmed' onclick=\"return do_search('user_".$param.".confirmed');\">"; if($_SESSION['nomination_sort']=='user_'.$param.'.confirmed') $return .= "<img src='".HTTP_SERVER.IMG_DIR.$_SESSION['nomination_order'].".png' /> "; $return .= "<b>Confirmed</b></a></nobr></td>
										<td align='center'><nobr><b>Confirm</b></nobr></td>
										<td align='center'><nobr><b>Delete</b></nobr></td>";
				if($_SESSION['access']=='0') { $return .= "<td><nobr><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?sort=user.celeb' onclick=\"return do_search('user.celeb');\">"; if($_SESSION['nomination_sort']=='user.celeb') $return .= "<img src='".HTTP_SERVER.IMG_DIR.$_SESSION['nomination_order'].".png' /> "; $return .= "<b>Is Celeb</b></a></nobr></td>"; }
			} else {
				$return .= "<td><nobr><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?sort=nomination.nomination_count' onclick=\"return do_search('nomination.nomination_count');\">"; if($_SESSION['nomination_sort']=='nomination.nomination_count') $return .= "<img src='".HTTP_SERVER.IMG_DIR.$_SESSION['nomination_order'].".png' /> "; $return .= "<b>Nomination Count</b></a></nobr></td>";
				if($_SESSION['access']=='0') { $return .= "<td><nobr><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?sort=nomination.vote_count' onclick=\"return do_search('nomination.vote_count');\">"; if($_SESSION['nomination_sort']=='nomination.vote_count') $return .= "<img src='".HTTP_SERVER.IMG_DIR.$_SESSION['nomination_order'].".png' /> "; $return .= "<b>Vote Count</b></a></nobr></td>"; }
				if($_SESSION['access']!='0') $return .= "<td align='center'><nobr><b>Your Vote</b></nobr></td>";
			}
			$return .= "</tr>";
			
			foreach($results as $r) {
				if($count >= $_SESSION['nomination_count_from'] && $count < ($_SESSION['nomination_count_from']+$_SESSION['nomination_count'])) {
					$return .= "<tr valign='top' "; if($count%2!=0) $return .= "bgcolor='#ECF5FC'"; $return .= ">";
					$return .= "<td>".$r[0]."</td>
											<td>".$r[1]."</td>
											<td>".$r[2]."</td>";
					if($detail) {
						$return .= "<td>".($r[3]?'yes':'no')."</td>
												<td align='center'><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?action=confirm&type=".$param."&user_id=".$r[4]."&nomination_id=".$r[5]."' onclick=\"return do_action('confirm', '".$param."', '".$r[4]."', '".$r[5]."');\"><img src='".HTTP_SERVER.IMG_DIR.($r[3]?'b_tick.png':'b_cross.png')."' title='".($r[3]?'Unconfirm':'Confirm')."' alt='Confirm/Unconfirm'></a></td>
												<td align='center'><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?action=delete&type=".$param."&user_id=".$r[4]."&nomination_id=".$r[5]."' onclick=\"return do_action('delete', '".$param."', '".$r[4]."', '".$r[5]."');\"><img src='".HTTP_SERVER.IMG_DIR."b_del.png' title='Delete' alt='Delete'></a></td>";
						if($_SESSION['access']=='0') $return .= "<td><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?action=markceleb&user_id=".$r[4]."&status=".$r[6]."' onclick=\"return mark_celeb('".$r[4]."', '".$r[6]."');\"><img src='".HTTP_SERVER.IMG_DIR.($r[6]?'b_tick.png':'b_cross.png')."' title='".($r[6]?'Mark as not a celebrity':'Mark as a celebrity')."' alt='Is Celeb'></a></td>";
					}	else {
						if($_SESSION['access']=='0') $return .= "<td>".$r[3]."</td>";
						if($_SESSION['access']!='0') {
							$db->Query("SELECT member_vote.* FROM member, member_vote, nomination WHERE nomination.id = member_vote.nomination_id AND member_vote.member_id = member.id AND member.username = '".$_SESSION['loggedin']."' AND nomination.id = '".$r[4]."';");
							if($db->getRow()) $voted = 1; else $voted = 0;
							$return .= "<td><a href='".HTTP_SERVER.ADMIN_DIR.$url[0].'/'.$url[1]."?action=membervote&nomination_id=".$r[4]."&status=".$voted."' onclick='return member_vote(\"".$r[4]."\", \"".$voted."\");'><img src='".HTTP_SERVER.IMG_DIR.($voted?'b_tick.png':'b_cross.png')."' title='".($voted?'Unvote':'Vote')."' alt='Vote/Unvote'></a></td>";
						}
					}
					$return .= "</tr>";
				}
				$count++;
			}
		} else $return .= "<tr><td colspan='5'><p>Sorry, no results.</p></td></tr>";
		$return .= "</table>";
		return $return;
	}
	
	function delete_nomination($user_id, $nomination_id) {
			$db = new CDatabase();
			$db->Connect();
			$db->Query("SELECT confirmed FROM user_nomination WHERE user_id='".$user_id."' AND nomination_id = '".$nomination_id."';");
			$db->getRow();
			if($db->access[0]=='1') $db->Query("UPDATE nomination SET nomination_count = (nomination_count-1) WHERE id = '".$nomination_id."';");
			$db->Query("DELETE FROM user_nomination WHERE user_id='".$user_id."' AND nomination_id = '".$nomination_id."';");
			return '';
	}

	function confirm_nomination($user_id, $nomination_id) {
			$db = new CDatabase();
			$db->Connect();
			$db->Query("SELECT confirmed FROM user_nomination WHERE user_id='".$user_id."' AND nomination_id = '".$nomination_id."';");
			if($db->GetRow()) $conf = $db->access[0];
			if($conf=='0') $db->Query("UPDATE nomination SET nomination_count = (nomination_count+1) WHERE id = '".$nomination_id."';");
			else $db->Query("UPDATE nomination SET nomination_count = (nomination_count-1) WHERE id = '".$nomination_id."';");
			$db->Query("UPDATE user_nomination SET confirmed = '".(($conf=='0')?1:0)."' WHERE user_id='".$user_id."' AND nomination_id = '".$nomination_id."';");
			return '';
	}

	function delete_vote($user_id, $nomination_id) {
			$db = new CDatabase();
			$db->Connect();
			$db->Query("SELECT confirmed FROM user_vote WHERE user_id='".$user_id."' AND nomination_id = '".$nomination_id."';");
			$db->getRow();
			if($db->access[0]=='1') $db->Query("UPDATE nomination SET vote_count = (vote_count-1) WHERE id = '".$nomination_id."';");
			$db->Query("DELETE FROM user_vote WHERE user_id='".$user_id."' AND nomination_id = '".$nomination_id."';");
			return '';
	}

	function confirm_vote($user_id, $nomination_id) {
			$db = new CDatabase();
			$db->Connect();
			$db->Query("SELECT confirmed FROM user_vote WHERE user_id='".$user_id."' AND nomination_id = '".$nomination_id."';");
			if($db->GetRow()) $conf = $db->access[0];
			if($conf=='0') $db->Query("UPDATE nomination SET vote_count = (vote_count+1) WHERE id = '".$nomination_id."';");
			else $db->Query("UPDATE nomination SET vote_count = (vote_count-1) WHERE id = '".$nomination_id."';");
			$db->Query("UPDATE user_vote SET confirmed = '".(($conf=='0')?1:0)."' WHERE user_id='".$user_id."' AND nomination_id = '".$nomination_id."';");
			return '';
	}
	
	function member_vote($nomination_id, $status) {
		$db = new CDatabase();
		$db->Connect();
		//get member_id who is making the vote
		$db->Query("SELECT id FROM member WHERE username = '".$_SESSION['loggedin']."';");
		$db->getRow();
		$member_id = $db->access[0];
		//get the category for which nomination is being voted
		$db->Query("SELECT category_id FROM nomination WHERE id = '".$nomination_id."';");
		$db->getRow();
		$category_id = $db->access[0];
		//count all the votes that this member made that was in that same category
		$db->Query("SELECT count(*) FROM member_vote, nomination 
									WHERE member_vote.nomination_id = nomination.id
									AND nomination.category_id = '".$category_id."'
									AND member_vote.member_id = '".$member_id."';");
		if($db->getRow()) {
			if($db->access[0]>=10 && !$status) return "<span class='error'>Sorry, but you've reached your vote limit. You need to unvote some other nomination in order to vote for this blog.</span>";
		}
		//if voted then unvote else if unvoted then vote
		if($status) {
			$db->Query("UPDATE nomination SET vote_count = (vote_count-1) WHERE id = '".$nomination_id."';");
			$db->Query("DELETE FROM member_vote WHERE nomination_id = '".$nomination_id."' AND member_id = '".$member_id."';");
		}	else {
			$db->Query("UPDATE nomination SET vote_count = (vote_count+1) WHERE id = '".$nomination_id."';");
			$db->Query("INSERT INTO member_vote(member_id, nomination_id) VALUES ('".$member_id."', '".$nomination_id."');");
		}
		return '';
	}
	
	function mark_celeb($user_id, $status) {
		$db = new CDatabase();
		$db->Connect();
		//if celeb then mark as not celeb else if not celeb then mark as celeb
		$db->Query("UPDATE user SET celeb = '".($status?0:1)."' WHERE id = '".$user_id."';");
		return '';
	}
	
?>